<?php
    session_start();
    if (!$_SESSION['user']){//判断用户是否登录
        header('Location: login.php');
        return;
    }
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>查询通讯录</title>
    <style>
        a{
            color: gray;
            text-decoration: none;
            cursor: pointer;
        }
        a:hover{
            color:red;
        }
        .new{
            text-align: right;
            width:480px;
        }
        h1{
            color:red;
        }
        table{
            width:480px;
            border:4px double red;
            border-spacing: 0;
        }
        th, td{
            border-bottom: 1px dotted red;
            border-right: 1px dotted red;
            padding: 6px 10px;
            text-align: center;
        }
        .status{
            text-align: right;
            width: 480px;
            margin: 6px 0;
            display: flex;
        }
        .status>p:nth-child(2){
            color: red;
            flex-grow: 1;
            text-align: left;
        }
        p{
            margin: 0;
        }
        label{
            margin-right: 10px;
        }
        html{
            position: relative;
            /*border: 20px solid red;*/
        }
        .mask{
            /*background-color: #999;*/
            display: none;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            width: 500px;
        }
        .msgBox{
            min-width: 300px;
            position: absolute;
            top: 100px;
            left: 80px;
            background-color: #ccc;
            border-radius: 10px;
            border: 4px double red;
            padding: 10px;
        }
        .msgBox h1{
            margin: 0;
        }
        .msgBox .msg{
            margin-bottom: 10px;
            color: darkslateblue;
        }
        .msgBox .btn{
            text-align: right;
        }
        .msgBox button{
            padding: 6px 20px;
            border-radius: 6px;
            border: 1px solid #999;
        }
        .msgBox button:hover{
            border: 1px solid #333;
        }
    </style>
</head>
<body>
    <h1>通讯录信息</h1>
    <div class="status">
        <p>欢迎你:</p>
        <p><?=$_SESSION['user']['xh'].$_SESSION['user']['name']?></p>
        <label><input type="checkbox" checked>删除时是否需要确认</label>
        <a href="logout.php">注销</a>
    </div>
    <?php
        $db = new PDO("mysql:host=localhost; dbname=db2;", 'root', 'root');
        $db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
        $ps = $db -> query('select * from students');
        echo "<table>";
        echo "<tr><th>学号</th><th>姓名</th><th>电话</th><th>管理</th></tr>";
        foreach ($ps as $r) {
            echo "<tr data-xh='",urlencode($r['xh']),"'><td>{$r['xh']}</td><td>{$r['name']}</td><td>{$r['tel']}</td><td>";
            if ($r['xh'] === $_SESSION['user']['xh'] || $_SESSION['user']['isAdmin']){
                echo "<a>删除</a> <a>修改</a>";
            }
            echo "</td></tr>";
        }
        echo '</table>'
    ?>
    <script>
        // let obj = document.querySelector('html')
        document.querySelector('table').addEventListener('click',async (e) => {
            let a = e.target
            if (a.tagName !== 'A')//点击的不是删除或修改超链接就直接返回
                return
            let tr = a.parentElement.parentElement //超链接所在的表格行
            let xh = tr.getAttribute('data-xh')
            if (a.innerText === '删除'){
                let besure = true//是否要执行删除操作，默认是要删除
                if (document.querySelector('input').checked){//需要用户确认吗
                    besure = await showDialog('你确认要删除 xh=' + xh + ' 的记录吗？',true,e)//让用户进行确认
                    // console.log('besure=',besure)
                }
                if (besure){//确认要进行删除记录
                    let response = await fetch('delete2.php?xh=' + xh)//异步请求
                    let result = await response.json()//返回JSON格式的数据
                    console.log(result)
                    if (result.ok){//成功删除记录
                        if (result.logout){//用户已经注销 , 重定向到登录页面
                            location.href = 'login.php'
                        }else {
                            tr.remove()
                        }
                    }else {//删除失败
                        await showDialog(result.msg,false,e)
                    }
                }
            }else if (a.innerText === '修改'){

            }

        })
        //多次设置onclick只有最后一次起作用
        // obj.onclick = e => {
        //     console.log(123)
        // }

        //多次设置 addEventListener，每次设置的函数在事件发生时都会被执行。
        //参数若为 true，函数在捕获阶段执行，默认的 false 代表在冒泡阶段执行。

        // obj.addEventListener('click',e => { // e-事件对象
        function showDialog(msg,showCancel,e){
            // console.log(e.target.tagName,e.pageY)
            // if (e.target.tagName !== 'A')
            //     return
            //Promise 对象用于异步操作，它表示一个尚未完成且预计在未来完成的异步操作。
            return new Promise((resolve, reject) => {
                let mask = document.querySelector('.mask')
                mask.style.display = 'block'
                let table = document.querySelector('table')
                let msgbox = document.querySelector('.msgBox')
                msgbox.querySelectorAll('button')[1].style.display = showCancel?'':'none'
                msgbox.querySelector('h1').innerText = showCancel?'确认框':'消息框'
                msgbox.querySelector('.msg').innerText = msg //设置要显示的信息
                let tableTop = table.offsetTop + table.clientTop
                let tr = e.target.parentElement.parentElement
                tr.style.backgroundColor = 'yellowgreen'
                let trHeight = tr.offsetHeight
                let top = parseInt((e.pageY - tableTop) / trHeight) * trHeight + tableTop + trHeight
                if (window.innerHeight - (e.clientY + top - e.pageY) < msgbox.offsetHeight){
                    top -= msgbox.offsetHeight + trHeight + 1
                }
                // let top = e.pageY
                msgbox.style.top = top + 'px'
                msgbox.style.left = '80px'
                msgbox.onclick = (e) => {
                    if (e.target.tagName === 'BUTTON'){
                        mask.style.display = 'none'
                        tr.style.backgroundColor = ''
                        resolve(e.target.innerText ==='确定') //返回用户选择的结果 true删除,false不删除
                    }
                }
            })
        }

        // document.querySelectorAll('td>a').forEach(a => {
        //     a.addEventListener('click',async (e) => {
        //         let tr = a.parentElement.parentElement
        //         let xh = tr.getAttribute('data-xh')
        //         console.log(a,a.innerText,xh)
        //         if (a.innerText === '删除'){//执行删除操作
        //             console.log('执行删除操作' + xh)
        //             console.log(document.querySelector('input').checked)
        //             let besure = true//是否要执行删除操作，默认是要删除
        //             if (document.querySelector('input').checked){//需要用户确认吗
        //                 besure = confirm('你确认要删除 xh=' + xh + ' 的记录吗？')//让用户进行确认
        //             }
        //             if (besure){//如果要执行删除
        //                 let response = await fetch('delete2.php?xh=' + xh)//异步请求
        //                 let result = await response.json()//返回JSON格式的数据
        //                 console.log(result)
        //                 if (result.ok){//成功删除记录
        //                     if (result.logout){//用户已经注销 , 重定向到登录页面
        //                         location.href = 'login.php'
        //                     }else {//从界面上移除被删除的记录
        //                         tr.remove()
        //                     }
        //                 }else {//删除失败
        //                     alert(result.msg)
        //                 }
        //             }
        //         } else if (a.innerText === '修改'){//执行修改操作
        //             console.log('执行修改操作' + xh)
        //             fetch('.php')
        //         }
        //     })
        // })
    </script>
    <div class="mask">
        <div class="msgBox">
            <h1>确认框</h1>
            <hr>
            <div class="msg">
                你确认删除吗？
            </div>
            <div class="btn">
                <button>确定</button>
                <button>取消</button>
            </div>
        </div>
    </div>
</body>
</html>